package com.killer.auth.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.killer.common.entity.Result;
import com.killer.common.util.CloneUtil;
import com.killer.common.util.DateUtil;
import com.killer.auth.service.IndexService;
import com.killer.goods.entity.Sku;
import com.killer.goods.entity.Spu;
import com.killer.goods.feign.SkuClient;
import com.killer.goods.feign.SpuClient;
import com.killer.search.entity.SkuInfo;
import com.killer.auth.util.BulkUtil;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkProcessor;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class IndexServiceImpl implements IndexService {

    @Autowired
    private SpuClient spuClient;
    @Autowired
    private SkuClient skuClient;

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public String importAll() {
        BulkProcessor bulkProcessor = BulkUtil.getBulkProcessor(restHighLevelClient);
        long startId=0l;
        String indexName= "goods-"+ DateUtil.format(DateUtil.getNow(), "yyyy-MM-dd-HH-mm-ss");
        List<Spu> spuList = getMarketableSpuList(startId);
        while (!CollectionUtils.isEmpty(spuList)) {
            for (Spu spu : spuList) {
                log.info("查询spuId:{}的sku列表", spu.getId());
                //查询sku列表
                List<Sku> skuList = getSkuListBySpuId(spu.getId());
                if (!CollectionUtils.isEmpty(skuList)) {
                    for (Sku sku : skuList) {
                        SkuInfo skuInfo = CloneUtil.convert(sku, new SkuInfo());
                        skuInfo.setSpecMap(JSONObject.parseObject(sku.getSpec(), Map.class));
                        bulkProcessor.add(new IndexRequest(indexName).source(JSONObject.toJSONString(skuInfo), XContentType.JSON));
                    }
                }
            }
            startId=spuList.get(spuList.size()-1).getId()+1;
            spuList=getMarketableSpuList(startId);
        }
        return indexName;
    }

    private List<Sku>  getSkuListBySpuId(Long supId) {
        Map<String,Object> params=new HashMap<>();
        params.put("spuId", supId);
        Result<List<Sku>> skuResult = skuClient.search(params);
        return skuResult==null?null:skuResult.getData();
    }

    private List<Spu> getMarketableSpuList(long startId) {
        Result<List<Spu>> resultList = spuClient.batchGetMarketableSpu(startId);
        return resultList == null ? null : resultList.getData();
    }


    @Override
    public void importGoodsBySpuId(Long spuId) {
        BulkProcessor bulkProcessor = BulkUtil.getBulkProcessor(restHighLevelClient);
        List<Sku> skuList = getSkuListBySpuId(spuId);
        if (!CollectionUtils.isEmpty(skuList)) {
            for (Sku sku : skuList) {
                bulkProcessor.add(new IndexRequest("goods").source(JSONObject.toJSONString(sku), XContentType.JSON));
            }
        }
    }

    @Override
    public void removeGoodsBySupId(Long spuId) throws IOException {
        DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest("goods").setQuery(QueryBuilders.boolQuery().filter(QueryBuilders.termQuery("spuId", spuId)));
        restHighLevelClient.deleteByQuery(deleteByQueryRequest, RequestOptions.DEFAULT);
    }
}
